import axios from 'axios'
import { MessageBox, Message, Notification } from 'element-ui'
import store from '@/store'
import { getToken, getExp, setToken, setExp, removeToken, getTokenType, removeTokenType, setTokenType,removeExp } from '@/utils/auth'
// create an axios instance
const service = axios.create({
  baseURL: '/work', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 // request timeout
})

/*是否有请求正在刷新token*/
window.isRefreshing = false
/*被挂起的请求数组*/
let refreshSubscribers = []
function onRrefreshed (token) {
  refreshSubscribers.map(cb => cb(token))
}
function subscribeTokenRefresh (cb) {
  refreshSubscribers.push(cb)
}

// request interceptor
service.interceptors.request.use(
  config => {
    const exps = getExp()
    const t = Date.parse(new Date()) / 1000
    if (exps !== undefined){
      // do something before request is sent
      const time = exps - t
      // if (time < 0) {
      //   MessageBox.confirm('登录失效，请重新登录', '温馨提示', {
      //     confirmButtonText: '重新登录',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     removeToken()
      //     removeTokenType()
      //     window.location.href = '/login'
      //   })
      //   return config
      // }
      const token = getToken()
      const type = getTokenType()
      /*判断token是否将要过期*/
      if (time < 300) {
        /*判断是否正在刷新*/
        if (!window.isRefreshing) {
          /*将刷新token的标志置为true*/
          window.isRefreshing = true
          /*发起刷新token的请求*/
          axios.post('/work/api/system/user/refreshToken', null, { headers: { 'Authorization': token,'TokenType': type }}).then(res => {
            /*将标志置为false*/
            window.isRefreshing = false
            setToken(res.data.data[0])
            setExp(res.data.data[1])
            setTokenType(res.data.data[2])
            /*执行数组里的函数,重新发起被挂起的请求*/
            onRrefreshed(res.data.data[0])
            /*执行onRefreshed函数后清空数组中保存的请求*/
            refreshSubscribers = []
          }) .catch(err => {
            console.log(err)
            Notification.error({
              title: '温馨提示',
              message: '登录失效，请重新登录'
            });
            removeExp()
            removeToken()
            removeTokenType()
            window.location.href = '/login'

          })
        }
        /*把请求(token)=>{....}都push到一个数组中*/
        let retry = new Promise((resolve, reject) => {
          /*(token) => {...}这个函数就是回调函数*/
          subscribeTokenRefresh((token) => {
            config.headers.Authorization = token
            config.headers.TokenType = getTokenType()
            /*将请求挂起*/
            resolve(config)
          })
        })
        return retry
      }
    }
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
      config.headers['TokenType'] = getTokenType()
    }
    if (config.method === 'post') {
      config.data = {
        ...config.data,
        _t: t
      }
    } else if (config.method === 'get') {
      config.params = {
        _t: t,
        ...config.params
      }
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (response.headers['content-type'] === 'application/x-msdownload') {
      return response
    }
    const res = response.data
    if (res.code !== 0) {
      Message({
        message: res.msg || 'error',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.code === -2) {
        removeToken()
        MessageBox.confirm(res.msg, '温馨提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // location.reload()
          removeExp()
          removeToken()
          removeTokenType()
          window.location.href = '/login'
        })
      } else if (res.code === -3) {
        console.log('自定义抛出')
      } else {
        MessageBox.confirm(res.msg, '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        })
      }
      return Promise.reject(res.msg || 'error')
    } else {
      return response
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
